<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>HTML to Image</title>
  <!-- 引入 html2canvas 库 -->
  <script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
</head>
<body>
  <!-- 您的 HTML 内容 -->
  <div id="content">
    <h1>Hello, World!</h1>
    <p>This is an example HTML content.</p>
  </div>

  <!-- 按钮用于触发截图 -->
  <button id="capture">Capture and Save as Image</button>

  <script>
    document.getElementById('capture').addEventListener('click', function () {
      // 使用 html2canvas 将页面内容转换为图片
      html2canvas(document.getElementById('content')).then(function (canvas) {
        // 创建一个新的 Canvas 元素，并将截图绘制到其中
        var newCanvas = document.createElement('canvas');
        newCanvas.width = canvas.width;
        newCanvas.height = canvas.height;
        var context = newCanvas.getContext('2d');
        context.drawImage(canvas, 0, 0, canvas.width, canvas.height);

        // 将 Canvas 转换为图片并保存
        var dataURL = newCanvas.toDataURL('image/png');
        var link = document.createElement('a');
        link.href = dataURL;
        link.download = 'screenshot.png';
        link.click();
      });
    });
  </script>
</body>
</html>
